import { getToolsByCategory, toolCategories } from '@/services/menuService';
import SearchIcon from '@mui/icons-material/Search';
import SecurityIcon from '@mui/icons-material/Security';
import SpeedIcon from '@mui/icons-material/Speed';
import StarIcon from '@mui/icons-material/Star';
import TrendingUpIcon from '@mui/icons-material/TrendingUp';
import {
    alpha,
    Box,
    Card,
    CardContent,
    Chip,
    Container,
    Grid,
    InputAdornment,
    Paper,
    TextField,
    Typography,
    useTheme,
    Zoom
} from '@mui/material';
import { motion } from 'framer-motion';
import { useEffect, useState } from 'react';
import ToolCard from '../components/ToolCard';

// 动画变体配置
const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
        opacity: 1,
        transition: {
            staggerChildren: 0.1
        }
    }
};

const itemVariants = {
    hidden: { y: 20, opacity: 0 },
    visible: {
        y: 0,
        opacity: 1,
        transition: {
            type: 'spring',
            stiffness: 100
        }
    }
};

const featureVariants = {
    hidden: { x: -20, opacity: 0 },
    visible: {
        x: 0,
        opacity: 1,
        transition: {
            type: 'spring',
            stiffness: 100
        }
    }
};

const HomePage = () => {
    const theme = useTheme();
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedCategory, setSelectedCategory] = useState('all');
    const [isLoaded, setIsLoaded] = useState(false);

    useEffect(() => {
        setTimeout(() => setIsLoaded(true), 300);
    }, []);

    // 根据分类和搜索词过滤工具
    const filteredTools = (() => {
        let result = getToolsByCategory(selectedCategory);
        if (searchTerm) {
            result = result.filter(tool =>
                tool.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                tool.description.toLowerCase().includes(searchTerm.toLowerCase())
            );
        }
        return result;
    })();

    // 特性数据
    const features = [
        {
            icon: <SpeedIcon sx={{ fontSize: 28 }} />,
            title: '极速处理',
            description: '毫秒级响应，本地处理更安全'
        },
        {
            icon: <SecurityIcon sx={{ fontSize: 28 }} />,
            title: '隐私保护',
            description: '数据不上传，完全本地化处理'
        },
        {
            icon: <StarIcon sx={{ fontSize: 28 }} />,
            title: '完全免费',
            description: '所有功能永久免费使用'
        },
        {
            icon: <TrendingUpIcon sx={{ fontSize: 28 }} />,
            title: '持续更新',
            description: '定期添加新工具和功能'
        }
    ];

    return (
        <>
            {/* 主横幅区域 */}
            <Box
                sx={{
                    mb: 4,
                    position: 'relative',
                    background: `linear-gradient(135deg, 
                        ${alpha(theme.palette.primary.main, 0.06)} 0%, 
                        ${alpha(theme.palette.secondary.main, 0.04)} 100%)`,
                    borderRadius: 3
                }}
            >
                <Container maxWidth="lg" sx={{ py: 4 }}>
                    {/* 搜索框 */}
                    <Zoom in={isLoaded} timeout={1000}>
                        <Box sx={{
                            display: 'flex',
                            justifyContent: 'center'
                        }}>
                            <TextField
                                variant="outlined"
                                placeholder="搜索工具..."
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                sx={{
                                    width: { xs: '100%', sm: '400px' },
                                    '& .MuiOutlinedInput-root': {
                                        borderRadius: '25px',
                                        backgroundColor: theme.palette.background.paper,
                                        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                                        transition: 'all 0.3s ease',
                                        '&:hover': {
                                            boxShadow: '0 4px 12px rgba(0,0,0,0.15)'
                                        },
                                        '&.Mui-focused': {
                                            boxShadow: `0 4px 12px ${alpha(theme.palette.primary.main, 0.3)}`
                                        }
                                    }
                                }}
                                InputProps={{
                                    startAdornment: (
                                        <InputAdornment position="start">
                                            <SearchIcon sx={{ color: 'text.secondary' }} />
                                        </InputAdornment>
                                    ),
                                }}
                            />
                        </Box>
                    </Zoom>
                </Container>
            </Box>

            <Container maxWidth="xl">
                {/* 工具列表 */}
                <motion.div
                    variants={containerVariants}
                    initial="hidden"
                    animate="visible"
                >
                    <Typography
                        variant="h4"
                        sx={{
                            mb: 3,
                            fontWeight: 700,
                            color: 'text.primary',
                            textAlign: 'center'
                        }}
                    >
                        {searchTerm ? `搜索结果 (${filteredTools.length})` : '精选工具'}
                    </Typography>

                    {/* 分类选择器 */}
                    <Box sx={{
                        display: 'flex',
                        justifyContent: 'center',
                        mb: 4,
                        flexWrap: 'wrap',
                        gap: 1
                    }}>
                        {toolCategories.map((category) => (
                            <Chip
                                key={category.id}
                                label={category.name}
                                onClick={() => setSelectedCategory(category.id)}
                                variant={selectedCategory === category.id ? 'filled' : 'outlined'}
                                sx={{
                                    borderRadius: '20px',
                                    px: 2,
                                    py: 0.5,
                                    fontSize: '0.875rem',
                                    fontWeight: 600,
                                    transition: 'all 0.3s ease',
                                    cursor: 'pointer',
                                    bgcolor: selectedCategory === category.id
                                        ? category.color
                                        : 'transparent',
                                    color: selectedCategory === category.id
                                        ? '#fff'
                                        : category.color,
                                    borderColor: category.color,
                                    '&:hover': {
                                        bgcolor: selectedCategory === category.id
                                            ? category.color
                                            : alpha(category.color, 0.1),
                                        transform: 'translateY(-2px)',
                                        boxShadow: `0 4px 12px ${alpha(category.color, 0.3)}`
                                    }
                                }}
                            />
                        ))}
                    </Box>

                    <Paper
                        elevation={0}
                        sx={{
                            p: { xs: 3, md: 4 },
                            bgcolor: 'background.paper',
                            borderRadius: 4,
                            border: `1px solid ${alpha(theme.palette.primary.main, 0.08)}`,
                            boxShadow: `0 8px 32px ${alpha(theme.palette.primary.main, 0.06)}`,
                            overflow: 'hidden',
                            mb: 8
                        }}
                    >
                        {filteredTools.length > 0 ? (
                            <Grid container spacing={{ xs: 3, md: 4 }}>
                                {filteredTools.map((tool, index) => (
                                    <Grid item xs={12} sm={6} lg={4} xl={3} key={tool.id}>
                                        <motion.div
                                            variants={itemVariants}
                                            custom={index}
                                        >
                                            <ToolCard
                                                id={tool.id}
                                                title={tool.title}
                                                description={tool.description}
                                                path={tool.path}
                                                category={tool.category}
                                            />
                                        </motion.div>
                                    </Grid>
                                ))}
                            </Grid>
                        ) : (
                            <Box sx={{ textAlign: 'center', py: 8 }}>
                                <SearchIcon
                                    sx={{
                                        fontSize: 80,
                                        color: 'text.disabled',
                                        mb: 2
                                    }}
                                />
                                <Typography
                                    variant="h6"
                                    color="text.secondary"
                                    sx={{ mb: 1 }}
                                >
                                    没有找到相关工具
                                </Typography>
                                <Typography
                                    variant="body2"
                                    color="text.disabled"
                                >
                                    尝试使用其他关键词搜索
                                </Typography>
                            </Box>
                        )}
                    </Paper>
                </motion.div>

                {/* 特性展示 */}
                {!searchTerm && (
                    <motion.div
                        variants={containerVariants}
                        initial="hidden"
                        animate="visible"
                    >
                        <Box sx={{ mb: 8 }}>
                            <Typography
                                variant="h4"
                                align="center"
                                sx={{
                                    mb: 6,
                                    fontWeight: 700,
                                    color: 'text.primary'
                                }}
                            >
                                为什么选择我们？
                            </Typography>
                            <Grid container spacing={4}>
                                {features.map((feature, index) => (
                                    <Grid item xs={12} sm={6} md={3} key={index}>
                                        <motion.div variants={featureVariants}>
                                            <Card
                                                sx={{
                                                    height: '100%',
                                                    textAlign: 'center',
                                                    borderRadius: 3,
                                                    border: `1px solid ${alpha(theme.palette.primary.main, 0.1)}`,
                                                    transition: 'all 0.3s ease',
                                                    '&:hover': {
                                                        transform: 'translateY(-4px)',
                                                        boxShadow: `0 8px 24px ${alpha(theme.palette.primary.main, 0.15)}`
                                                    }
                                                }}
                                                elevation={0}
                                            >
                                                <CardContent sx={{ p: 4 }}>
                                                    <Box
                                                        sx={{
                                                            color: theme.palette.primary.main,
                                                            mb: 2
                                                        }}
                                                    >
                                                        {feature.icon}
                                                    </Box>
                                                    <Typography
                                                        variant="h6"
                                                        sx={{
                                                            mb: 2,
                                                            fontWeight: 600
                                                        }}
                                                    >
                                                        {feature.title}
                                                    </Typography>
                                                    <Typography
                                                        variant="body2"
                                                        color="text.secondary"
                                                        sx={{ lineHeight: 1.6 }}
                                                    >
                                                        {feature.description}
                                                    </Typography>
                                                </CardContent>
                                            </Card>
                                        </motion.div>
                                    </Grid>
                                ))}
                            </Grid>
                        </Box>
                    </motion.div>
                )}
            </Container>
        </>
    );
};

export default HomePage;